<template>
  <div class="btn-wrap">
    <n-input
      v-show="state.mode === 'input'"
      :value="props.value"
      @input="emits('update:value', $event)"
      @change="emits('change', $event)"
    />
    <div v-show="state.mode === 'select'" class="tag-wrap">
      <n-tag
        v-for="(item, index) in state.selectValues"
        :key="index"
        style="margin-right: 4px; margin-bottom: 5px"
        size="small"
        closable
        @close="onRemoveSelect(index)"
        >{{ item.name }}</n-tag
      >
    </div>
    <Dialog :data-mode="props.dataMode" :multiple="props.multiple" @select="onSelect" />
  </div>
</template>

<script setup lang="ts">
  import { reactive } from 'vue'
  import Dialog from './Dialog.vue'
  import type { Assign, InputMode, DataMode } from './type.d'

  const emits = defineEmits(['update:value', 'change'])
  const props = defineProps<{ value: string; dataMode: DataMode; multiple: boolean }>()

  const state = reactive({ selectValues: [] as Assign[], mode: 'input' as InputMode })
  const onSelect = (assigns: Assign[]) => {
    state.mode = 'select'

    state.selectValues = assigns
    const ids = state.selectValues.map((val: any) => val.id)
    emits('change', ids.join(';'))
  }
  const onRemoveSelect = (idx: number) => {
    emits('update:value', '')

    state.selectValues.splice(idx, 1)
    const ids = state.selectValues.map((val: any) => val.id)
    emits('change', ids.join(';'))

    if (ids.length === 0) {
      state.mode = 'input'
    }
  }
</script>

<style lang="scss" scoped>
  .btn-wrap {
    display: flex;
    align-items: center;
    gap: 4px;
  }
  .tag-wrap {
    line-height: normal;
    padding-top: 5px;
    width: 100%;
    border: 1px solid rgb(224, 224, 230);
    border-radius: 3px;
    padding-left: 12px;
    padding-right: 12px;
  }
</style>
